import traceback
from models.hotspot import Hotspot
from extensions import db
from services.constants import PLATFORM_CONFIG
from services.platform_crawl_manager import (
    get_platform_latest_crawl_at,
)

# 从数据库删除非最新抓取的热点数据
def delete_old_hotspot_data(time:int) -> None:
    """删除非最新抓取的热点数据

    Parameters:
        time: 时间戳，占位，无作用
    
    """
    try:
        print("开始删除过期数据")
        total_deleted = 0
        # 获取最新抓取时间
        for platform in PLATFORM_CONFIG.keys():
            # 获取最新抓取时间
            latest_crawl_at = get_platform_latest_crawl_at(platform)
            for section in PLATFORM_CONFIG[platform]["sections"].keys():
                platform_id = PLATFORM_CONFIG[platform]["id"]
                section_id = PLATFORM_CONFIG[platform]["sections"][section]
                # 平台旧数据数量
                old_data_count = Hotspot.query.filter(
                    Hotspot.platform == platform_id,
                    Hotspot.section == section_id,
                    Hotspot.crawl_at != latest_crawl_at,
                ).count()
                total_deleted += old_data_count

                # 删除非最新抓取的热点数据
                Hotspot.query.filter(
                    Hotspot.platform == platform_id,
                    Hotspot.section == section_id,
                    Hotspot.crawl_at != latest_crawl_at,
                ).delete()
                print(f"删除 {platform} - {section} 的旧数据, 数量: {old_data_count}")
        
        db.session.commit()
        print(f"删除过期数据成功, 删除数量: {total_deleted}")
    except Exception as e:
        db.session.rollback()
        print(f"删除旧数据失败:", e)
        print("详细错误信息:")
        traceback.print_exc()
        raise e